#!/usr/bin/env node

import prompts from 'prompts'
import { red, green, bold } from 'kolorist'
import path from 'path'
import { fileURLToPath } from 'url'
import { createVue3Naive } from './vue3-naive-cli/index.js'
import { createVue3Element } from './vue3-element-cli/index.js'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

// 验证项目名称
function isValidPackageName(projectName: string) {
  return /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(projectName)
}

// 将项目名称转换为合法的包名
function toValidPackageName(projectName: string) {
  return projectName
    .trim()
    .toLowerCase()
    .replace(/\s+/g, '-')
    .replace(/^[._]/, '')
    .replace(/[^a-z0-9-~]+/g, '-')
}

// 模板选项
const TEMPLATE_CHOICES = [
  {
    title: 'Vue3 + Naive UI',
    value: 'vue3-naive',
    description: '基于Vue3和Naive UI的模板',
    action: createVue3Naive
  },
  {
    title: 'Vue3 + Element Plus',
    value: 'vue3-element',
    description: '基于Vue3和Element Plus的模板',
    action: createVue3Element
  }
]

async function init() {
  // 选择模板
  const { template } = await prompts({
    type: 'select',
    name: 'template',
    message: '请选择项目模板',
    choices: TEMPLATE_CHOICES,
    onState: (state) => {
      if (state.aborted) {
        process.nextTick(() => {
          process.exit(1)
        })
      }
    }
  })

  if (!template) {
    console.log(red('✖') + ' 请明确选择一个模板')
    process.exit(1)
  }

  // 执行对应模板的创建逻辑
  const selectedTemplate = TEMPLATE_CHOICES.find(t => t.value === template)
  if (!selectedTemplate) {
    console.log(red('✖') + ' 无效的模板选择')
    process.exit(1)
  }
  
  // 获取项目名称并去除前后空格
  const { projectName } = await prompts({
    type: 'text',
    name: 'projectName',
    message: '请输入项目名称:',
    initial: selectedTemplate.value === 'vue3-naive' 
      ? 'vue3-naive-project' 
      : 'vue3-element-project',
    validate: value => {
      const trimmed = value.trim()
      if (!trimmed) return '项目名称不能为空'
      if (!isValidPackageName(trimmed)) return '项目名称包含非法字符'
      return true
    }
  })

  if (!projectName) {
    console.log(red('✖') + ' 项目创建已取消')
    process.exit(1)
  }

  // 确保只执行一次创建
  await selectedTemplate.action(projectName.trim())
}

init().catch(err => {
  console.error(red('错误：'), err)
  process.exit(1)
})